const {exec} = require('../db/mysql')

const login = async (openid)=>{
    // console.log(open)
    const sql = `
        select * from users
        where openid='${openid}';
    `
    const rows = await exec(sql)
    return rows[0]||null
}
const update =async (openid,session_key)=>{
    const date=new Date().getTime()
    const sql = `
        update users set  lastTime='${date}',session_key='${session_key}'
        where openid='${openid}'
    `
    const updateData = await exec(sql)
    if(updateData.affectedRows > 0){
        return true
    }
    return false
}
const registered = async (openid,session_key)=>{
    const date=new Date().getTime()
    const sql = `
        insert into users(openid,createDate,lastTime,session_key)
        values ('${openid}','${date}','${date}','${session_key}')
    `
    const insertData=exec(sql);
    return {
        id:insertData.id
    }
}

const setUserInfo = async (id,info)=>{
    const sql = `
        update users set avatarUrl='${info.avatarUrl}',city='${info.city}',
        country='${info.country}',gender='${info.gender}',
        nickName='${info.nickName}',province='${info.province}'
        where id=${id}
    `
    const updateData = await exec(sql)
    if(updateData.affectedRows > 0){
        return true
    }
    return false
}

const getUserInfo = async (id)=>{
    const sql = `
        select * from users
        where id=${id}
    `
    const rows = await exec(sql)
    return rows[0]||null
}
module.exports={
    login,
    registered,
    update,
    getUserInfo,
    setUserInfo
}